(function($) {  
    $.fn.microblogBox = function(options) {
        var element = this; 
        var textarea = null;   
        var entries = null;

        var defaults = {  
            db: null 
        };  

        var options = $.extend(defaults, options); 

        //db.execute('DELETE FROM twits WHERE 1');

        var add = function ()
        {
	        if ($(textarea).val())
	        {
		        $(entries).text('');
		        options.db.execute("INSERT INTO entries VALUES (?, strftime('%s', 'now'))", [$(textarea).val()]);
		        $(textarea).val('');
		        reload();
	        }
        };

        var reload = function ()
        {

	        var rs = options.db.execute("SELECT *, datetime(Timestamp, 'unixepoch') FROM entries ORDER BY Timestamp DESC");

	        while (rs.isValidRow()) 
	        {
		        $('<div class="entry">').append($('<div class="box">')).append($('<div class="text">').text(rs.field(0))).append($('<div class="date">').text('@' + rs.field(2))).appendTo(entries);
		        rs.next();
	        }
	
	        rs.close();
        };

        var microblogBox = function() {
            options.db.execute('CREATE TABLE IF NOT EXISTS entries (Phrase text, Timestamp int)');

            textarea = $('<textarea class="newEntry">');
            entries = $('<div>');
            $(element)
                .append(textarea)
                .append($('<br />'))
                .append($('<input type="button" value="Add!" class="addButton" />').click(add))
                .append(entries);
        };

        microblogBox();
        reload();

    }
})(jQuery);
